'use strict';

const Controller = require('egg').Controller;
const jwt = require('jsonwebtoken');
class UserController extends Controller {
    async login() {
        const { ctx } = this;
        const {name,password} = ctx.request.body;
        if(!name || !password){
            ctx.body = {
                code:2,
                mes:'缺少参数'
            }
            return;
        }
        //当前用户是否注册
        let user = await ctx.service.user.getuser(name);
        if(user.length == 0){
            ctx.body = {
                code:3,
                mes:'该用户还没有注册，请先注册'
            }
            return;
        }
        //登录
        // const md5 = crypto.createHash('md5');
        // const update = md5.update(pwd);
        // const newpwd = update.digest('hex');
        try{
            let res = await ctx.service.user.login(name,ctx.helper.cryptopwd(password));
            //生成token sign(用户信息,密钥,过期时间)
            let token = jwt.sign({...res[0]},ctx.app.config.keys,{expiresIn:'10h'});
            ctx.body = {
                code:0,
                token,
                uid:res[0].userId,
                mes:'登录成功'
            }
        }catch(e){
            ctx.body = {
                code:1,
                mes:'登录失败'
            }
        } 
    }
    async registry() {
        const { ctx } = this;
        const {name,realName,password} = ctx.request.body;
        console.log(name,realName,password)
        if(!name || !realName|| !password){
            ctx.body = {
                code:2,
                mes:'缺少参数'
            }
            return;
        }
        //判断当前用户是否存在
        let user = await ctx.service.user.getuser(name);
        if(user.length > 0){
            ctx.body = {
                code:3,
                mes:'该用户已经注册，请直接登录'
            }
            return;
        }
        //添加
        // const md5 = crypto.createHash('md5');
        // const update = md5.update(password);
        // const newpwd = update.digest('hex');
        let res = await ctx.service.user.registry(name,realName,ctx.helper.cryptopwd(password));
        if(res.affectedRows == 1){
            ctx.body = {
                code:0,
                mes:'注册成功'
            }
        } else {
            ctx.body = {
                code:1,
                mes:'注册失败'
            }
        }
    }
}

module.exports = UserController;
